<!--todo 搜索 myTable.reload 提示未定义-->
<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">权限管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!console">首页</a>
          <a><cite>权限管理</cite></a>
        </span>
    </div>
    <div class="fsh-rightPanel">
        <div class="layui-anim layui-anim-upbit">
            <div class="layui-btn-group">
                <button class="layui-btn" id="btn-expand">全部展开</button>
                <button class="layui-btn" id="btn-fold">全部折叠</button>
                <button class="layui-btn btn-primary" id="menu_add">新建顶级菜单</button>
<!--                <button class="layui-btn btn-primary" id="flushPerCache">刷新缓存</button>-->
            </div>
        </div>
    </div>
    <div class="layui-card-body">
<!--        <div class="layui-form toolbar">-->
<!--            搜索：-->
<!--            <select id="auth-search-key">&ndash;&gt;-->
<!--                                <option value="">-请选择-</option>-->
<!--                                <option value="permissionName">权限名称</option>-->
<!--                                <option value="permissionKey">权限标识</option>-->
<!--                            </select>-->
<!--            <input id="auth-search-value" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;-->
<!--            <button id="auth-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>-->
<!--&lt;!&ndash;            <button id="auth-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>&ndash;&gt;-->
<!--        </div>-->


        <!-- 数据表格 -->
        <table class="layui-table" id="auth-table" lay-filter="auth-table"></table>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="auth-state">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs"lay-event="add">添加子权限</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="auth-model">
    <form id="auth-form" lay-filter="auth-form" class="layui-form model-form">
        <input name="permission_id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">权限名称</label>
            <div class="layui-input-block">
                <input name="permissionName" placeholder="请输入权限名称" type="text" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权限标识</label>
            <div class="layui-input-block">
                <input name="permissionKey" placeholder="请输入权限标识" type="text" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">访问地址</label>
            <div class="layui-input-block">
                <input name="url" placeholder="请输入访问地址" type="text" class="layui-input"
                       lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">访问方法</label>
            <div class="layui-input-block">
                <select name="method">
                    <option value="GET">GET</option>
                    <option value="POST">POST</option>
                    <option value="PATCH">PATCH</option>
                    <option value="DELETE">DELETE</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">是否菜单</label>
            <div class="layui-input-block">
                <input type="radio" class="layui-input" value="Y"  name="menu_flag" title="是" >
                <input type="radio" class="layui-input" value="N"  name="menu_flag" title="否" checked>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">父权限标识</label>
            <div class="layui-input-block">
                <input name="parent_key" placeholder="请输入父权限标识" type="text" class="layui-input"
                       lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">所有父权限标识</label>
            <div class="layui-input-block">
                <input name="parent_keys" placeholder="请输入所有父权限标识" type="text" class="layui-input"
                       lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
            <button class="layui-btn" lay-filter="auth-form-submit" lay-submit>保存</button>
        </div>
    </form>
</script>


<script>
    layui.use(['form', 'table', 'treetable','util', 'config', 'admin'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var treetable = layui.treetable;
        var config = layui.config;
        var form = layui.form;
        var util = layui.util;
        var admin = layui.admin;

        // 渲染表格
        layer.load(2);
        var myTable = treetable.render({
                treeColIndex: 0,//树形图标显显示在第几列
                treeSpid: 0,//顶级pid
                treeIdName: 'permissionKey',//id
                treePidName: 'parent_key',//pid
                elem: '#auth-table',//要渲染的表格数据
                url: config.base_server + 'api-sys/api/per/getlist',//列表加载路径
                where: {
                    access_token: config.getToken().access_token
                },
                page: false,
                treeDefaultClose: true,//不全部展开
                // treeLinkage: true,        // 父级展开时是否自动展开所有子级
                cols: [[
                    // {type: 'numbers'}, 加上以后不会变树
                    {field: 'permissionName', sort: true, title: '权限名称',width:300},
                    {field: 'permissionKey', sort: true, title: '权限标识'},
                    {field: 'parent_key', sort: true, title: '父权限'},
                    {field: 'parent_keys', sort: true, title: '所有父权限'},
                    {field: 'url', sort: true, title: '访问地址'},
                    {field: 'method', sort: true, title: '访问方法', width: 110},
                    {field: 'createDate', sort: true, title: '创建时间'},
                    {templet: '#auth-state',align: 'center', title: '操作', width: 200}
                ]],
                done: function () {
                    layer.closeAll('loading');
                }
            });

        // 工具条点击事件
        table.on('tool(auth-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (layEvent === 'del') { // 删除
                doDelete(obj);
            } else if (layEvent === 'add') { // 添加子权限
                var subData = {
                    addSub: true,
                    parent_key :data.permissionKey,
                    parent_keys :data.parent_keys + "," + data.permissionKey,
                    permissionKey : data.permissionKey + "_",
                    parent_name: data.permissionName
                };
                showAddModel(subData);
        }
        });

        //刷新缓存
        $('#flushPerCache').click(function () {
            $.ajax({
                url: config.base_server + 'api-sys/api/per/flush',
                type: 'get',
                success: function(data){
                    if(data.success){layer.msg("刷新缓存成功!");}
                }
            });
        });

        // 删除
        var doDelete = function (obj) {
            layer.confirm('确定要删除吗？', function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('api-sys/api/per/del/'+obj.data.permission_id, {  }, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        obj.del();
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'DELETE');
            });
        };
        // 新建顶级菜单
        $("#menu_add").click(function () {
            var subData = {
                addSub: true,
                parent_key : 0,
                parent_keys : 0,
                permissionKey : "",
                parent_name: "顶级",
                method: 'GET',
                url: "#"
            };
            showAddModel(subData);

        });

        // 显示编辑弹窗
        var showEditModel = function (data) {
            layer.open({
                type: 1,
                title: data ? '修改权限' : '添加权限',
                area: '450px',
                offset: '120px',
                content: $('#auth-model').html(),
                success: function () {
                    $('#auth-form')[0].reset();
                    $('#auth-form').attr('method', 'POST');
                    if (data) {
                        $("input[name='parent_key']").attr('disabled',true);
                        $("input[name='parent_keys']").attr('disabled',true);
                        form.val('auth-form', data);
                        $('#auth-form').attr('method', 'POST');
                    }
                }
            });
        };
        //显示添加子权限和新建顶级菜单
        var showAddModel = function (data) {
            layer.open({
                type: 1,
                title: data.parent_key === 0 ? '新建顶级菜单' : '添加子权限',
                area: '450px',
                offset: '120px',
                content: $('#auth-model').html(),
                success: function () {
                    $('#auth-form')[0].reset();
                    $('#auth-form').attr('method', 'POST');
                    if (data) {
                        $("input[name='parent_key']").attr('disabled',true);
                        $("input[name='parent_keys']").attr('disabled',true);
                        form.val('auth-form', data);
                        $('#auth-form').attr('method', 'POST');
                    }
                }
            });
        };

        // 表单提交事件
        form.on('submit(auth-form-submit)', function (data) {
            layer.load(2);
            if (data.field.permission_id){
                admin.req('api-sys/api/per/update', JSON.stringify(data.field), function (data) {
                    layer.closeAll('loading');
                    console.log(data);
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        table.reload('auth-table');
                        layer.closeAll('page');
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'PATCH');
            }else{
                admin.req('api-sys/api/per/add', JSON.stringify(data.field), function (data) {
                    layer.closeAll('loading');
                    console.log(data);
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        table.reload('auth-table');
                        layer.closeAll('page');
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'POST');
            }

            return false;
        });

        // 搜索按钮点击事件
        $('#auth-btn-search').click(function () {
            var key = $('#auth-search-key').val();
            var value = $('#auth-search-value').val();
            var data = {};
            data[key] = value;
            console.log(data)
            // table.reload('role-table', {where: data});
            myTable.reload({where: data});
        });
        $('#btn-expand').click(function () {
            treetable.expandAll('#auth-table');
        });

        $('#btn-fold').click(function () {
            treetable.foldAll('#auth-table');
        });
    });

</script>
